package com.dabai.playlistdown;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.FileUtils;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dabai.playlistdown.pojo.MusicInfo;
import com.dabai.playlistdown.utils.MusicAdapter;
import com.download.library.DownloadImpl;
import com.download.library.DownloadListenerAdapter;
import com.download.library.Extra;

import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    String TAG = "dabaizzz";

    String playlist_id = "";
    ArrayList<MusicInfo> musics;

    String downapi = "http://music.163.com/song/media/outer/url?id=";

    ListView lv;
    ProgressBar pb;
    ArrayAdapter adapter;

    private MaterialDialog md1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        musics = new ArrayList<>();

        lv = findViewById(R.id.lv);
        pb = findViewById(R.id.progressBar);

        md1 = new MaterialDialog.Builder(this)
                .title("输入歌单ID")
                .cancelable(false)
                .inputRangeRes(5, 15, R.color.colorAccent)
                .inputType(InputType.TYPE_CLASS_TEXT)
                .input("歌单ID", "2761133889", new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(MaterialDialog dialog, CharSequence input) {
                        playlist_id = "" + input;
                    }
                })
                .positiveText("解析").onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        start1();
                    }
                })
                .neutralText("退出").onNeutral(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finish();
                    }
                })
                .show();



        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final MusicInfo mi = musics.get(i);

                ImageView img = view.findViewById(R.id.pic1);
                final TextView title1 = view.findViewById(R.id.title1);

                final File downfile = new File("/sdcard/Music/NetEaseAnalysis/", mi.getAuthor() + " - " + mi.getTitle() + ".mp3");

                new MaterialDialog.Builder(MainActivity.this)
                        .title("" + mi.getTitle())
                        .content("歌曲地址:" + downapi + mi.getId())
                        .positiveText("下载歌曲")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                if (downfile.exists()) {
                                    Toast.makeText(MainActivity.this, "此歌曲已经下载!", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                DownloadImpl.getInstance()
                                        .with(getApplicationContext())
                                        .target(downfile)
                                        .url(downapi + mi.getId())
                                        .enqueue(new DownloadListenerAdapter() {
                                            @Override
                                            public void onStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength, Extra extra) {
                                                super.onStart(url, userAgent, contentDisposition, mimetype, contentLength, extra);
                                            }

                                            @Override
                                            public void onProgress(String url, long downloaded, long length, long usedTime) {
                                                super.onProgress(url, downloaded, length, usedTime);

                                                if (length < 10) {
                                                    title1.setText(mi.getTitle() + " - 下载失败");
                                                    
                                                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
                                                        Toast.makeText(MainActivity.this, mi.getTitle() + " - 下载失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                    
                                                    return;
                                                }

                                                title1.setText(mi.getTitle() + " - " + saveOneBitOneRound((float) downloaded / (float) length * 100) + "%");
                                            }

                                            @Override
                                            public boolean onResult(Throwable throwable, Uri path, String url, Extra extra) {

                                                if (!title1.getText().toString().contains("下载失败")) {
                                                    title1.setText(mi.getTitle() + " - 下载完成");
                                                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
                                                        Toast.makeText(MainActivity.this, mi.getTitle() + " - 下载完成", Toast.LENGTH_SHORT).show();
                                                    }
                                                } else {
                                                    downfile.delete();
                                                }

                                                return super.onResult(throwable, path, url, extra);
                                            }
                                        });
                            }
                        })
                        .neutralText("取消")
                        .icon(img.getDrawable())
                        .show();
            }
        });


        //检查代码是否拥有这个权限
        int checkResult = this.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        //if(!=允许),抛出异常
        if (checkResult != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); // 动态申请读取权限
            }
        } else {
            File dir = new File("/sdcard/Music/NetEaseAnalysis");
            File dir2 = new File("/sdcard/Pictures/NetEaseAnalysis");

            if (!dir.exists() || !dir2.exists()) {
                dir.mkdirs();
                dir2.mkdirs();
            }
        }

    }

    //菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.downall:

                for (final MusicInfo mi:
                     musics) {

                            downfile(downapi+mi.getId(),mi.getAuthor() + " - " + mi.getTitle());

                }
                Toast.makeText(this, "开始下载了，请保证软件后台运行!下载时长根据你的歌曲数量决定!", Toast.LENGTH_SHORT).show();

                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public void downfile(String url, final String title){

        File downfile1 = new File("/sdcard/Music/NetEaseAnalysis/", title + ".mp3");

        if (downfile1.exists()) {
            //Toast.makeText(MainActivity.this, "此歌曲已经下载!", Toast.LENGTH_SHORT).show();
            return;
        }

        downLoad(url,downfile1);

    }



    /**
     * 从服务器下载文件
     * @param path 下载文件的地址
     * @param file 文件名字
     */
    public static void downLoad(final String path, final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setReadTimeout(5000);
                    con.setConnectTimeout(5000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
                    if (con.getResponseCode() == 200) {
                        InputStream is = con.getInputStream();//获取输入流
                        FileOutputStream fileOutputStream = null;//文件输出流
                        if (is != null) {
                            fileOutputStream = new FileOutputStream(file);//指定文件保存路径，代码看下一步
                            byte[] buf = new byte[1024];
                            int ch;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
                            }
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    @Override
    protected void onResume() {
        super.onResume();

        try {
            ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ContentResolver cr = getContentResolver();
            ClipData clipdata = clip.getPrimaryClip();

            if (clip != null) {

                //从剪贴板数据中获取第一项
                ClipData.Item item = clipdata.getItemAt(0);
                final String text = item.coerceToText(this).toString();

                if (text.contains("music.163.com/playlist")){
                    new MaterialDialog.Builder(this)
                            .title("提示")
                            .content("检测到剪切板包含歌单链接，是否解析")
                            .positiveText("确认")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    playlist_id = text.substring(text.indexOf("playlist")+9);
                                    playlist_id = playlist_id.substring(0,playlist_id.indexOf("/"));

                                    md1.dismiss();

                                    start1();
                                }
                            })
                            .negativeText("取消")
                            .show();

                }
            }

        } catch (Exception e) {

        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {


        if (requestCode == 1) {
            /**
             * 申请权限
             */
            int checkResult = getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);

            if (checkResult != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "没有权限,不能运行", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                File dir = new File("/sdcard/Music/NetEaseAnalysis");
                File dir2 = new File("/sdcard/Pictures/NetEaseAnalysis");

                if (!dir.exists() || !dir2.exists()) {
                    dir.mkdirs();
                    dir2.mkdirs();
                }

            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    /**
     * 保留一位小数，进行四舍五入（该方法经测试 较为精准）
     *
     * @param d
     * @return
     */
    public static double saveOneBitOneRound(double d) {
        String str = String.format("%.1f", d);
        double c = Double.parseDouble(str);
        return c;
    }

    private void start1() {
        pb.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {

                    Connection.Response res = Jsoup.connect("https://api.mlwei.com/music/api/wy/?key=523077333&cache=1&type=songlist&id=" + playlist_id)
                            .timeout(10000).ignoreContentType(true).execute();//.get();
                    String body = res.body();

                    JSONObject jsonObject2 = JSON.parseObject(body);
                    JSONArray jsonArray = jsonObject2.getJSONArray("Body");

                    musics.clear();

                    int size = jsonArray.size();
                    for (int i = 0; i < size; i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        if (jsonObject.containsKey("url")) {

                            MusicInfo mi = new MusicInfo();
                            mi.setId(jsonObject.getString("id"));
                            mi.setTitle(jsonObject.getString("title"));
                            mi.setAuthor(jsonObject.getString("author"));
                            mi.setPic(jsonObject.getString("pic"));
                            mi.setUrl(jsonObject.getString("url"));

                            musics.add(mi);

                        }

                    }

                } catch (IOException e) {
                    Log.d(TAG, "run: " + e);
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new MusicAdapter(MainActivity.this, R.layout.item_music, musics);
                        lv.setAdapter(adapter);
                        pb.setVisibility(View.GONE);
                    }
                });

            }
        }).start();
    }
}
